<template>
    <!-- 从确认订单过来 -->
    <van-address-list
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="ToAddressAdd"
        @edit="ToAddressEdit"
        @select="OnCartSelect"
        v-if="action === 'select'"
    />

    <!-- 从收货地址列表过来 -->
    <van-address-list
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="ToAddressAdd"
        @edit="ToAddressEdit"
        @select="OnAddressSelect"
        v-else
    />
</template>

<script setup>
    const { proxy } = getCurrentInstance();

    // 默认地址
    const active = ref(0);

    // 收获地址列表
    const list = reactive([]);

    // 用户信息
    const business = proxy.$business;

    // 接收关键字
    const action = ref(proxy.$route.query.action ?? '');

    onBeforeMount(() => GetAddressData());

    const GetAddressData = async () =>
    {
        let result = await proxy.$POST({
            url:'/address/index',
            params:{
                busid:business.value.id
            }
        });

        if(result.code === 1)
        {
            result.data.map((item) => {
                // 找出默认的收获地址
                if(item.status == 1) active.value = item.id

                // 重组收获地址结构
                list.push({
                    id: item.id,
                    name: item.consignee,
                    tel: item.mobile,
                    address: `${item.region_text} ${item.address}`,
                    isDefault: item.status == 1 ? true : false
                })
            })
        }else
        {
            proxy.$fail(result.msg);

            return false;
        }
    }

    // 收获地址添加
    const ToAddressAdd = async () => proxy.$router.push('/address/add');

    // 收获地址的编辑
    const ToAddressEdit = async (item) => proxy.$router.push({path:'/address/edit',query:{id:item.id}});

    // 切换默认的收获地址
    const OnAddressSelect = async (item, index) => 
    {
        var result = await proxy.$POST({
            url: '/address/select',
            params: {
                busid: proxy.$business.value.id,
                id: item.id
            }
        })

        if(result.code === 1)
        {
            // 成功就修改默认的状态
            list.map(value => {
                // 把所有的地址全部修改为非默认地址
                value.isDefault = false

                // 刚刚切换的地址 设置为默认的
                if(value.id == item.id) value.isDefault = true
            })
        }else
        {
            proxy.$fail(result.msg);

            return false;
        }
    }

    const OnCartSelect = (item) =>
    {
        let address = {
            id:item.id,
            name:item.name,
            tel:item.tel,
            region_text:item.address
        }

        proxy.$address.value = address;

        proxy.$router.back();
    }
</script>
